# polls/admin.py
from django.contrib import admin
from .models import Question, Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 2
    fields = ['choice_text', 'votes']
    readonly_fields = ['votes']

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    list_display = ('question_text', 'pub_date', 'end_date', 'is_active', 'was_published_recently')
    list_filter = ['pub_date', 'is_active']
    search_fields = ['question_text']
    fieldsets = [
        ('基本信息', {
            'fields': ['question_text', 'is_active']
        }),
        ('日期信息', {
            'fields': ['pub_date', 'end_date'],
            'classes': ['collapse']
        }),
    ]
    inlines = [ChoiceInline]
    actions = ['make_active', 'make_inactive']
    
    def make_active(self, request, queryset):
        queryset.update(is_active=True)
    make_active.short_description = "激活所选投票"
    
    def make_inactive(self, request, queryset):
        queryset.update(is_active=False)
    make_inactive.short_description = "停用所选投票"

@admin.register(Choice)
class ChoiceAdmin(admin.ModelAdmin):
    list_display = ('question', 'choice_text', 'votes', 'percentage')
    list_filter = ['question']
    search_fields = ['choice_text']